<template>
  <div class="server-main">
    <!-- <el-form label-width="70px">
      <el-form-item label="本体模型">
        <el-select v-model="ontologyModelId" placeholder="请选择" @change="changeCate">
          <el-option v-for="item in cateOptions" :key="item.ontologyAllId" :label="item.ontologyAllName"
            :value="item.ontologyAllId">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form> -->

    <el-form :inline="true" v-model="modelData" class="search-form">
      <el-form-item label="本体类" class="form-input">
        <el-input v-model.trim="modelData.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态" class="form-input">
        <el-select v-model="modelData.state">
          <el-option label="全部" value="2"></el-option>
          <el-option label="启用" value="0"></el-option>
          <el-option label="禁用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button id="btn" type="primary" size="small" @click="onSubmit(1)"
          >查询</el-button
        >
      </el-form-item>
    </el-form>

    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text">本体类管理</span>
        <div>
          <el-button type="primary" size="small" @click="openCreateOntology"
            >新增本体类</el-button
          >
        </div>
      </div>
      <el-table
        ref="categoryTableRef"
        :data="tableList"
        row-key="id"
        :cell-style="{ color: '#333333' }"
        :header-cell-style="{ background: '#F3F4F7', color: '#000000' }"
      >
        <el-table-column
          label="ID"
          width="60"
          align="center"
          class-name="drag-handle"
        >
          <template slot-scope="scope">
            <i class="el-icon-rank"></i>
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="本体类名称"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="parentName"
          label="父级本体类"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column prop="state" label="状态" width="200" align="center">
          <template slot-scope="scope">
            <i class="little-circle-blue" v-if="scope.row.state === 0"></i>
            <i class="little-circle-red" v-else></i>
            <span>{{ +scope.row.state === 0 ? "启用" : "禁用" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="200">
          <template slot-scope="scope">
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="openEditOntology(scope.row)"
              >编辑</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="goDetail(scope.row)"
              >属性</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="changeStatus(scope.row)"
              >{{ +scope.row.state === 0 ? "禁用" : "启用" }}
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        small
        layout="total, prev, pager, next, sizes, jumper"
        :page-sizes="[10, 20, 30]"
        :total="total"
        :hide-on-single-page="!total"
        :page-size.sync="modelData.pageSize"
        :pager-count="7"
        :current-page="modelData.pageNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog
      title="新增本体类"
      :visible.sync="dialogFormVisible1"
      @close="afterDialogClose(1)"
    >
      <el-form
        :model="modelParams1"
        :rules="rules"
        ref="dialogForm1"
        label-position="right"
        label-width="120px"
      >
        <el-form-item
          label="父级本体类:"
          prop="parentName"
          class="dialog-inline"
        >
          <el-cascader
            ref="refSubCat"
            v-model="modelParams1.parentName"
            placeholder=""
            @change="hidePanelDom"
            :props="{ checkStrictly: true }"
            :options="parentList"
            :show-all-levels="false"
            filterable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="本体类名称:" prop="name" class="dialog-inline">
          <el-input
            maxlength="50"
            show-word-limit
            v-model.trim="modelParams1.name"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitDialogForm1" :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑本体类"
      :visible.sync="dialogFormVisible2"
      @close="afterDialogClose(2)"
    >
      <el-form
        :model="modelParams2"
        :rules="rules"
        ref="dialogForm2"
        label-position="right"
        label-width="120px"
      >
        <el-form-item
          label="父级本体类:"
          prop="parentName"
          class="dialog-inline"
        >
          <el-input v-model.trim="modelParams2.parentName" :readonly="true">
          </el-input>
        </el-form-item>
        <el-form-item label="本体类名称:" prop="name" class="dialog-inline">
          <el-input
            maxlength="50"
            show-word-limit
            v-model.trim="modelParams2.name"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitDialogForm2" :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import Sortable from "sortablejs";
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "OntologyManagement",
  components: {},
  data: () => {
    return {
      parentList: null,
      oldName: "", // 旧的本体名称
      modelData: {
        name: "", // 本体类别名称
        state: "2", // 状态 0 启用，1禁用，2全部
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      cateOptions: [], // 本体模型列表
      ontologyModelId: "", // 本体模型的 id
      tableList: [], // 本体类别列表
      property: [], // 本体类别(节点)的属性列表
      total: 0, // 数据总条数
      loading: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      editOntologyId: null, // 编辑本体类别的id
      modelParams1: {
        name: "", // 本体类别名称
        parentName: null, // 父级本体类
      },
      modelParams2: {
        name: "", // 本体类别名称
        parentName: "", // 父级本体类
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入本体类名称",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      containerDom: (state) => state.server.containerDom,
      ontologyAllId: (state) => state.ontologyModel.ontologyAllId,
    }),
  },
  watch: {
    ontologyAllId(val) {
      this.getModelList(val);
    },
    "$route.path": {
      handler: function () {
        // 之后用路由守卫优化初次进入页面调用两次接口的问题
        this.getModelList(this.ontologyAllId);
      },
      immediate: true,
    },
  },
  mounted() {
    this.initSortable();
  },
  methods: {
    // 获取本体模型列表
    // getOntologyModelOptions() {
    //   let params = null;
    //   return this.$axios.get(this.$api.ontologyModel.xinbiaoObj.searchall, {
    //     params
    //   })
    // },

    // changeCate(id) {
    //   let obj = this.cateOptions.find(item => {
    //     return item.ontologyAllId === id;
    //   });
    //   this.ontologyModelId = obj.ontologyAllId;
    //   this.getModelList();
    // },

    // 拖拽功能
    initSortable() {
      const target = this.$refs.categoryTableRef.$el.querySelector(
        ".el-table__body-wrapper .el-table__body tbody"
      );
      new Sortable(target, {
        handle: ".drag-handle",
        draggable: ".el-table__row",
        animation: 150,
        onEnd: (evt) => {
          const { newIndex, oldIndex } = evt;
          if (newIndex === oldIndex) {
            return;
          }
          // 更新数据
          const copyData = cloneDeep(this.tableList);
          const targetRow = copyData[oldIndex];
          // 更新本地数据 与拖拽显示保持一致
          copyData.splice(oldIndex, 1);
          copyData.splice(newIndex, 0, targetRow);
          this.$set(this, "tableList", copyData);
          this.$axios
            .put(this.$api.ontologyModel.xinbiaoObj.changeSort, {
              newSort: newIndex + 1,
              ontologyId: targetRow.id,
            })
            .then((res) => {
              this.$message.success(res.message || "操作成功");
            })
            .catch(() => {
              this.$message.success("操作失败");
              // 失败后 直接从新请求数据
              this.getModelList();
            });
        },
      });
    },
    // 获取事件查询列表
    getModelList(allId) {
      const {
        pageNum,
        pageSize,
        state: ontologyState,
        name: ontologyName,
      } = this.modelData;
      let params = {
        ontologyAllId: allId ? allId : this.ontologyAllId,
        ontologyState,
        ontologyName,
        pageNum,
        pageSize,
      };
      this.$axios
        .get(this.$api.ontologyModel.xinbiaoObj.searchontology, {
          params,
        })
        .then((res) => {
          let data = res.data.data;
          this.tableList = data.list;
          this.total = data.total;
          // this.modelData.pageSize = data.pageSize;
          this.modelData.pageNum = data.pageNum;
          this.$utils.backtop(this.containerDom);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 查询
    onSubmit(pageNum) {
      this.modelData.pageNum = pageNum ? pageNum : this.modelData.pageNum;
      this.getModelList();
    },
    // 修改当前页码
    handleCurrentChange(page) {
      this.modelData.pageNum = page;
      this.getModelList();
    },
    // 修改每页条数
    handleSizeChange(e) {
      this.modelData.pageSize = e;
      this.getModelList();
    },
    // 跳转详情页
    goDetail(item) {
      // debugger;
      const { id, name: concept } = item;
      this.$router.push(
        `/ontologyModel/ontologyCategoryProperty/property/${id}/${concept}`
      );
    },
    // 修改状态
    changeStatus(item) {
      let { id: ontologyId, state } = item;
      let params = {
        ontologyId,
        ontologyAllId: this.ontologyAllId,
      };
      if (+state === 0) {
        // 点击禁用时
        this.$confirm("是否禁用当前本体类?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.disableOntology(params);
          })
          .catch(() => {});
      } else {
        this.enableOntology(params);
      }
    },
    disableOntology(params) {
      this.$axios
        .post(this.$api.ontologyModel.xuekuiObj.disableOntology, params)
        .then((res) => {
          if (res.data.code !== 200) {
            this.$message.warning(res.data.message);
            return;
          }
          this.$message.success("状态更改成功");
          this.onSubmit();
        })
        .catch((err) => {
          this.$message.warning("状态更改失败");
          console.error(err);
        });
    },
    enableOntology(params) {
      this.$axios
        .post(this.$api.ontologyModel.xuekuiObj.enableOntology, params)
        .then(() => {
          this.$message.success("状态更改成功");
          this.onSubmit();
        })
        .catch((err) => {
          this.$message.warning("状态更改失败");
          console.error(err);
        });
    },
    // 打开编辑本体框(获取节点信息)
    openEditOntology(row) {
      this.dialogFormVisible2 = true;
      const { id, property, name, parentName } = row;
      this.oldName = name;
      this.modelParams2.name = name;
      this.modelParams2.parentName = parentName ? parentName : "无";
      this.editOntologyId = id;
      this.property = property;
    },
    async getParentNodes(code) {
      let params = {
        // ontologyAllId: this.ontologyModelId,
        ontologyAllId: this.ontologyAllId,
        removeId: code === null ? code : this.editOntologyId,
      };
      let res = await this.$axios.get(
        this.$api.ontologyModel.xuekuiObj.getParentNodes,
        {
          params,
        }
      );
      if (res.data.code !== 200) {
        this.$message.error(res.data.message);
      } else {
        this.hideSubPanelData(res.data.data);
        this.parentList = res.data.data;
      }
    },
    // 删除children:[]项
    hideSubPanelData(obj) {
      if (Array.isArray(obj)) {
        obj.length > 0 &&
          obj.map((item) => {
            if (item.children.length === 0) {
              delete item.children;
            } else {
              this.hideSubPanelData(item.children);
            }
          });
      } else {
        this.$message.warning("数据格式出错");
      }
      return obj;
    },
    // 选中后关闭级联下拉框
    hidePanelDom(e) {
      if (e.length && this.$refs.refSubCat) {
        this.$refs.refSubCat.dropDownVisible = false;
      }
    },

    // 模态框关闭后
    afterDialogClose(num) {
      if (num === 1) {
        this.$refs["dialogForm1"].resetFields();
        return;
      }
      this.$refs["dialogForm2"].resetFields();
    },
    // 打开新增本体框
    async openCreateOntology() {
      let res = await this.getParentNodes(null);
      console.log("res", res);
      this.dialogFormVisible1 = true;
      // return true
    },
    // 取消
    resetDialogForm() {
      this.dialogFormVisible1 = false;
      this.dialogFormVisible2 = false;
    },
    // 确定
    submitDialogForm1() {
      this.$refs.dialogForm1.validate((valid) => {
        if (valid) {
          this.createOntology();
          this.dialogFormVisible1 = false;
        } else {
          return false;
        }
      });
    },
    submitDialogForm2() {
      this.$refs.dialogForm2.validate((valid) => {
        if (valid) {
          this.editOntology();
          this.dialogFormVisible2 = false;
        } else {
          return false;
        }
      });
    },
    // 创建本体
    createOntology() {
      const { name: ontologyName, parentName: parentId } = this.modelParams1;
      let params = {
        parentId:
          parentId === null
            ? parentId
            : parentId.splice(parentId.length - 1, 1)[0],
        ontologyName,
        // ontologyAllId: this.ontologyModelId,
        ontologyAllId: this.ontologyAllId,
      };
      this.loading = true;
      this.$axios
        .post(this.$api.ontologyModel.xuekuiObj.addOntology, params)
        .then((res) => {
          let code = res.data.code;
          if (+code !== 200) {
            this.$message.warning(res.data.message);
            this.loading = false;
            return;
          }
          this.loading = false;
          this.dialogFormVisible = false;
          this.onSubmit();
          this.$message.success("新增成功!");
        })
        .catch((error) => {
          this.loading = false;
        });
    },

    // 编辑本体类别
    editOntology() {
      const { name: ontologyName } = this.modelParams2;
      if (this.oldName === ontologyName) return;
      let params = {
        // ontologyAllId: this.ontologyModelId,
        ontologyAllId: this.ontologyAllId,
        ontologyId: this.editOntologyId,
        ontologyName,
      };
      this.loading = true;
      this.$axios
        .post(this.$api.ontologyModel.xuekuiObj.updateOntology, params)
        .then((res) => {
          let code = res.data.code;
          if (+code !== 200) {
            this.$message.warning(res.data.message);
            this.loading = false;
            return;
          }
          this.loading = false;
          this.dialogFormVisible = false;
          this.$message.success("编辑成功");
          this.onSubmit();
        })
        .catch((error) => {
          this.loading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.server-main {
  position: relative;

  .search-form {
    padding: 16px 32px;
    border-radius: 4px;
    background: #ffffff;

    .el-form-item {
      margin-bottom: 0;
    }

    .form-input {
      margin-right: 32px;

      /deep/ .el-input__inner {
        width: 240px;
        height: 32px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid #e0e0e0;
      }
    }
  }

  .el-select {
    /deep/ .el-input__inner {
      width: 240px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid #e0e0e0;
    }
  }

  .server-table {
    margin-top: 16px;
    padding: 16px 32px 64px;
    border-radius: 4px;
    background: #ffffff;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
      }

      margin-bottom: 10px;
    }

    .little-circle-blue {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #55c898;
      position: relative;
      right: 4px;
      top: -2px;
    }

    .little-circle-red {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #ee5564;
      position: relative;
      right: 6px;
      top: -2px;
    }

    /deep/ .el-table__row {
      // &.sortable-drag {
      //   background-color: #409eff99;
      // }
      .drag-handle {
        cursor: pointer;
      }
    }
  }

  .ontology-edit {
    padding: 0 10px;

    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }

  /deep/ .el-table__append-wrapper {
    padding: 10px;
  }

  .el-pagination {
    float: right;
    margin-top: 20px;

    .form-input /deep/ .el-input {
      width: 200px;
    }

    /deep/ .el-input__inner {
      height: 22px;
    }
  }

  /deep/ .el-dialog {
    width: 500px;
    border-radius: 5px;

    .el-dialog__body {

      .el-form-item {
        .el-cascader {
          width: 300px;
        }
      }
    }
  }

  .dialog-inline {
    /deep/ .el-form-item__content {
      width: 300px;
    }

    button.el-button {
      background-color: $--color-primary !important;
      color: #fff !important;
      line-height: 1.2;
    }
  }
}
</style>
